// Our global variable that tells us were online
jQueryAPI.Network = {};
jQueryAPI.Network.monitorCheckURL = 'http://google.com';
jQueryAPI.Network.pollInterval = 300000; //for testing - 5000;

/**
 * The function to execute when we have a internet connection
 */
jQueryAPI.Network.Online = function(){
	jQueryAPIOnline = true;
	
	function iconLoadComplete( event ) {
		if (air.NativeApplication.supportsSystemTrayIcon) {
    	air.NativeApplication.nativeApplication.icon.bitmaps = new Array(event.target.content.bitmapData);
      air.NativeApplication.nativeApplication.icon.tooltip = 'jQuery API Is Online';
			
			if (!DebugMode || ForceUpdate) {
	  		jQueryAPI.Update.InvokeApplicationUpdate({
	  			'updateXML': 'http://jquery-api-browser.googlecode.com/svn/branches/update/update.xml'
	  		});
	  	}
    }
	}
	
  var iconLoader = new runtime.flash.display.Loader();
  iconLoader.contentLoaderInfo.addEventListener(air.Event.COMPLETE, iconLoadComplete);
  iconLoader.load(new air.URLRequest('app:/assets/images/jQueryAPIOnline.png'));
};

/**
 * The function to execute when offline
 */
jQueryAPI.Network.Offline = function(){
	jQueryAPIOnline = false;
	
	function iconLoadComplete ( event ) {
		if (air.NativeApplication.supportsSystemTrayIcon) {
			air.NativeApplication.nativeApplication.icon.bitmaps = new Array(event.target.content.bitmapData);
			air.NativeApplication.nativeApplication.icon.tooltip = 'jQuery API Is Offline';
		}	
	}
	
	var iconLoader = new runtime.flash.display.Loader();
  iconLoader.contentLoaderInfo.addEventListener(air.Event.COMPLETE, iconLoadComplete);
  iconLoader.load(new air.URLRequest('app:/assets/images/jQueryAPIOffline.png'));
};

/**
 * The main network loop handler
 * @param {Object} event The callback event
 */
jQueryAPI.Network.MainLoop = function(event){
	switch (event.code) {
		case "Service.available":
			//we are online
			if (DebugMode) air.trace('jQueryAPI Is Online');
			jQueryAPI.Network.Online();
		break;
		case "Service.unavailable":
			if (DebugMode) air.trace('jQueryAPI Is Offline');
			jQueryAPI.Network.Offline();
		break;
	}
};

/**
 * The main network initialization function
 */
jQueryAPI.Network.Initialize = function(){
	if (!ForceOffline) {
  	if (DebugMode) 
  		air.trace('Starting Network Loop');
  	var url = new air.URLRequest(jQueryAPI.Network.monitorCheckURL);
  	var monitor = new air.URLMonitor(url);
  	monitor.pollInterval = jQueryAPI.Network.pollInterval;
  	monitor.addEventListener(air.StatusEvent.STATUS, jQueryAPI.Network.MainLoop);
  	monitor.start();
  } else {
		if (DebugMode) air.trace('jQueryAPI Has Been Forced Offline');
		jQueryAPI.Network.Offline();
	}
};
